package com.aids_malaria.ui.setting;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.adapter.RoleManagerAdapter;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.MultiDeleteRole;
import com.aids_malaria.http.response.Role;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class RoleManagerSettingActivity extends BaseActivity implements RoleManagerAdapter.Option{

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.cb_check_all)
    CheckBox cb_check_all;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<Role> mData = new ArrayList<>();
    private RoleManagerAdapter roleManagerAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_role_setting;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.setting_role_manage));
        initRefreshLayout();
        cb_check_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = cb_check_all.isChecked();
                for (int i=0; i<mData.size(); i++){
                    mData.get(i).setCheck(checked);
                    roleManagerAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getRole();
    }

    private void initRefreshLayout() {
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                getRole();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getRole();
            }
        });
    }

    private void initRecycleView() {
        refresh_layout.setEnableLoadMore(false);
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        roleManagerAdapter = new RoleManagerAdapter(mContext,R.layout.item_role_manager,mData,this);
        rv_data.setAdapter(roleManagerAdapter);
        roleManagerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putBoolean(RoleManagerCreateEditActivity.KEY_IS_CREATE, false);
                bundle.putSerializable(RoleManagerCreateEditActivity.KEY_ROLE,mData.get(position));
                startActivity(RoleManagerCreateEditActivity.class,bundle);
            }
        });
    }

    @OnClick({R.id.iv_add, R.id.iv_subtract})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_add:
                Bundle bundle = new Bundle();
                bundle.putBoolean(RoleManagerCreateEditActivity.KEY_IS_CREATE, true);
                startActivity(RoleManagerCreateEditActivity.class,bundle);
                break;
            case R.id.iv_subtract:
                List<MultiDeleteRole> multiDeleteRoleList = new ArrayList<>();
                for (int i=0; i<mData.size(); i++){
                    if(mData.get(i).isCheck()){
                        MultiDeleteRole multiDeleteRole = new MultiDeleteRole();
                        multiDeleteRole.setRole_id(mData.get(i).getRole_id());
                        multiDeleteRoleList.add(multiDeleteRole);
                    }
                }
                if(multiDeleteRoleList.size()>0){
                    String dataJson = GsonUtil.beanToJson(multiDeleteRoleList);
                    LogUtil.d("dataJson:-----------"+ dataJson);
                    multiDeleteRole(dataJson);
                }else{
                    ToastUtil.showToast(getString(R.string.delete_null));
                }
                break;
        }
    }

    /**
     * 获取角色数据
     *
     */
    private void getRole() {
        String roleName = et_name.getText().toString().trim();
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getRole(roleName)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<Role>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<Role> data) throws Exception {
                        mData.clear();
                        mData.addAll(data);
                        roleManagerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 删除多个角色
     * @param data 数据格式举例：[{"role_id":"test4"},{"role_id":"teset4"}]
     * @return
     */
    private void multiDeleteRole(String data) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).multiDeleteRole(requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(ResourceUtil.getString(R.string.operate_success));
                        getRole();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    @Override
    public void onItemCheck(int position, boolean isCheck) {
        mData.get(position).setCheck(isCheck);
        int totalselect = 0;
        for (int i = 0; i < mData.size() ; i++) {
            if (mData.get(i).isCheck()){
                totalselect++;
            }
        }
        if (totalselect < mData.size() ){
            cb_check_all.setChecked(false);
        }
    }

}
